<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <!-- <el-form-item label="企业名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业名称"
          clearable
          maxlength="10"
          show-word-limit
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
            <el-form-item label="企业简称" prop="shortName">
                <el-input maxlength="10" show-word-limit v-model="queryParams.shortName" placeholder="请输入企业简称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="企业编号" prop="enterpriseCode">
                <el-input v-model="queryParams.enterpriseCode" placeholder="请输入企业编号" clearable maxlength="20"
                    show-word-limit @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="联系人" prop="contactPerson">
                <el-input v-model="queryParams.contactPerson" placeholder="请输入联系人" clearable maxlength="10"
                    show-word-limit @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable maxlength="11"
                    show-word-limit @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['business:enterprise:add']">新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table ref="table" lazy :load="load" row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" v-loading="loading"
            :data="enterpriseList" @selection-change="handleSelectionChange">
            <el-table-column label="企业名称" prop="enterpriseName" min-width="200" :show-overflow-tooltip="true" />
            <el-table-column label="企业简称" align="center" prop="shortName" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="企业编号" align="center" prop="enterpriseCode" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="企业类型" align="center" prop="enterpriseType" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="法人代表" align="center" prop="legalPerson" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="联系人" align="center" prop="contactPerson" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="联系电话" align="center" prop="contactPhone" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="电子邮箱" align="center" prop="email" min-width="150" :show-overflow-tooltip="true" />
            <!-- <el-table-column label="企业地址" align="center" prop="address" min-width="150" :show-overflow-tooltip="true" /> -->
            <el-table-column label="成立日期" align="center" prop="establishDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.establishDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="经营范围" align="center" prop="businessScope" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="营业执照编号" align="center" prop="licenseNumber" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="纳税识别号" align="center" prop="taxNumber" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="center" min-width="100" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <el-switch v-if="scope.row.hierarchyType == 1" v-model="scope.row.enterpriseStatus"
                        :active-value="0" :inactive-value="1"
                        @change="handleStatusChange(scope.row, 'enterpriseStatus')"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="报告状态" align="center" min-width="100" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <el-switch v-if="scope.row.hierarchyType == 1" v-model="scope.row.reportStatus" active-value="0"
                        inactive-value="1" @change="handleStatusChange(scope.row, 'reportStatus')"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" min-width="150" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130" fixed="right">
                <template slot-scope="scope">
                    <!-- <el-button size="mini" type="text" @click="handleBitMatrix(scope.row)"
                        v-hasPermi="['business:enterprise:bitMatrix']">企业二维码</el-button> -->
                    <el-button size="mini" type="text" @click="handleAdd(scope.row)" v-if="scope.row.hierarchyType != 2"
                        v-hasPermi="['business:enterprise:add']">新增</el-button>
                    <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
                        v-hasPermi="['business:enterprise:edit']">修改</el-button>
                    <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                        v-hasPermi="['business:enterprise:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改企业基本信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <!-- <el-form-item label="上级企业ID" prop="parentId">
                    <el-input v-model="form.parentId" placeholder="请输入上级企业ID" />
                </el-form-item> -->
                <el-form-item label="企业名称" prop="enterpriseName">
                    <el-input maxlength="20" show-word-limit v-model="form.enterpriseName" placeholder="请输入企业名称" />
                </el-form-item>
                <div v-if="form.parentId == 0">
                    <el-form-item label="企业简称" prop="shortName">
                        <el-input maxlength="10" show-word-limit v-model="form.shortName" placeholder="请输入企业简称" />
                    </el-form-item>
                    <el-form-item label="企业编号" prop="enterpriseCode">
                        <el-input maxlength="20" show-word-limit v-model="form.enterpriseCode" placeholder="请输入企业编号" />
                    </el-form-item>
                    <el-form-item label="法人代表" prop="legalPerson">
                        <el-input maxlength="10" show-word-limit v-model="form.legalPerson" placeholder="请输入法人代表" />
                    </el-form-item>
                    <el-form-item label="联系人" prop="contactPerson">
                        <el-input maxlength="10" show-word-limit v-model="form.contactPerson" placeholder="请输入联系人" />
                    </el-form-item>
                    <el-form-item label="联系电话" prop="contactPhone">
                        <el-input maxlength="11" show-word-limit v-model="form.contactPhone" placeholder="请输入联系电话" />
                    </el-form-item>
                    <el-form-item label="电子邮箱" prop="email">
                        <el-input maxlength="20" show-word-limit v-model="form.email" placeholder="请输入电子邮箱" />
                    </el-form-item>
                    <!-- <el-form-item label="企业地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入企业地址" />
                </el-form-item> -->
                    <el-form-item label="成立日期" prop="establishDate">
                        <el-date-picker clearable v-model="form.establishDate" type="date" value-format="yyyy-MM-dd"
                            placeholder="请选择成立日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="营业执照编号" prop="licenseNumber">
                        <el-input maxlength="10" show-word-limit v-model="form.licenseNumber" placeholder="请输入营业执照编号" />
                    </el-form-item>
                    <el-form-item label="纳税识别号" prop="taxNumber">
                        <el-input maxlength="10" show-word-limit v-model="form.taxNumber" placeholder="请输入纳税识别号" />
                    </el-form-item>
                    <el-form-item label="状态" prop="enterpriseStatus">
                        <el-radio-group v-model="form.enterpriseStatus">
                            <el-radio v-for="dict in enterpriseStatusList" :key="dict.id" :label="dict.id">{{ dict.name
                            }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="报告状态" prop="reportStatus">
                        <el-radio-group v-model="form.reportStatus">
                            <el-radio v-for="dict in reportStatusList" :key="dict.id" :label="dict.id">{{ dict.name
                            }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="经营范围" prop="businessScope">
                        <el-input maxlength="10" show-word-limit v-model="form.businessScope" type="textarea"
                            placeholder="请输入内容" />
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input rows="3" maxlength="100" show-word-limit v-model="form.remark" type="textarea"
                            placeholder="请输入内容" />
                    </el-form-item>
                </div>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog title="企业二维码" :visible.sync="bitMatrixopen" width="700px" append-to-body>
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <el-button :loading="loadingbitMatrix" type="primary" size="mini" @click="handleDownLoad"
                        v-hasPermi="['business:bitMatrix:downLoad']">下载</el-button>
                </div>
                <div ref="exportContainer" class="export-content">
                    <div>
                        <img :src="baseForm.img" class="content-image" />
                    </div>
                    <div>
                        <div class="text-content" v-if="baseForm.enterpriseName">企业名称：{{ baseForm.enterpriseName }}
                        </div>
                        <!-- <div class="text-content" v-if="baseForm.factoryName">厂区名称：{{ baseForm.factoryName }}</div> -->
                        <div class="text-content" v-if="baseForm.enterpriseDeptName">部门名称：{{ baseForm.enterpriseDeptName
                        }}
                        </div>
                    </div>
                </div>
            </el-card>
        </el-dialog>
    </div>
</template>

<script>
import { bitMatrix, listEnterprise, getEnterprise, delEnterprise, addEnterprise, updateEnterprise } from "@/api/company/index";
import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';
export default {
    name: "Enterprise",
    data() {
        return {
            loadingbitMatrix: false,
            bitMatrixopen: false,
            baseForm: {
                img: ''
            },
            nodeChildrenMap: new Map(), // 缓存子节点数据
            loadedNodes: new Set(), // 记录已加载的节点
            parentId: "",
            maps: new Map(),
            reportStatusList: [
                {
                    id: '0',
                    name: "可查看",
                },
                {
                    id: '1',
                    name: "不可查看",
                }
            ],
            enterpriseStatusList: [
                {
                    id: 0,
                    name: "启用",
                },
                {
                    id: 1,
                    name: "禁用",
                }
            ],
            // 是否展开，默认全部展开
            isExpandAll: true,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 企业基本信息表格数据
            enterpriseList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                parentId: null,
                enterpriseName: null,
                shortName: null,
                enterpriseCode: null,
                hierarchyType: null,
                enterpriseType: null,
                legalPerson: null,
                contactPerson: null,
                contactPhone: null,
                email: null,
                address: null,
                establishDate: null,
                businessScope: null,
                licenseNumber: null,
                taxNumber: null,
                enterpriseStatus: null,
                reportStatus: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                email: [
                    {
                        type: "email",
                        message: "请输入正确的邮箱地址",
                        trigger: ["blur", "change"]
                    }
                ],
                enterpriseName: [
                    { required: true, message: "企业名称不能为空", trigger: "blur" }
                ],
                enterpriseCode: [
                    { required: true, message: "企业编号不能为空", trigger: "blur" }
                ],
                legalPerson: [
                    { required: true, message: "法人代表不能为空", trigger: "blur" }
                ],
                contactPerson: [
                    { required: true, message: "联系人不能为空", trigger: "blur" }
                ],
                contactPhone: [
                    { required: true, message: "联系电话不能为空", trigger: "blur" },
                    {
                        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                        message: "请输入正确的手机号码",
                        trigger: "blur"
                    }
                ],
            }
        };
    },
    created() {
        this.getList();
    },
    methods: {
        async handleDownLoad() {
            this.loadingbitMatrix = true;
            try {
                const container = this.$refs.exportContainer;
                // 使用html2canvas转换DOM为Canvas
                const canvas = await html2canvas(container, {
                    useCORS: true, // 解决跨域图片问题
                    scale: 2,      // 提高输出质量
                    backgroundColor: '#ffffff' // 设置背景色
                });

                // 将Canvas转换为图片并下载
                canvas.toBlob(blob => {
                    saveAs(blob, '二维码.png');
                    this.loadingbitMatrix = false;
                });
            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error('图片导出失败');
                this.loadingbitMatrix = false;
            }
        },
        handleBitMatrix(row) {
            bitMatrix(row.id).then(res => {
                let base64Data = res.base64;
                this.baseForm = res.result
                this.bitMatrixopen = true
                this.$set(this.baseForm, 'img', base64Data);
            })
        },
        // 修改状态
        handleStatusChange(row, type) {
            this.$modal.confirm('确认要修改状态吗？').then(() => {
                return updateEnterprise({
                    id: row.id,
                    enterpriseStatus: row.enterpriseStatus,
                    reportStatus: row.reportStatus
                });
            }).then(() => {
                this.$modal.msgSuccess("修改成功");
                this.getList()
            }).catch(() => {
                if (type == 'enterpriseStatus') {
                    row.enterpriseStatus = row.enterpriseStatus == 0 ? 1 : 0;
                } else {
                    row.reportStatus = row.reportStatus == "0" ? "1" : "0";
                }
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                parentId: null,
                enterpriseName: null,
                shortName: null,
                enterpriseCode: null,
                hierarchyType: null,
                enterpriseType: null,
                legalPerson: null,
                contactPerson: null,
                contactPhone: null,
                email: null,
                address: null,
                establishDate: null,
                businessScope: null,
                licenseNumber: null,
                taxNumber: null,
                enterpriseStatus: 0,
                reportStatus: '0',
                remark: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd(row) {
            this.reset();
            if (!row.id) {
                this.form.hierarchyType = 1
                this.form.parentId = 0
            } else {
                this.form.parentId = row.id
                if (row.hierarchyType == 1) {
                    this.form.hierarchyType = 2
                } else {
                    this.form.hierarchyType = 3
                }
            }
            this.open = true;
            this.title = "添加企业基本信息";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getEnterprise(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改企业基本信息";
            });
        },
        refreshLoadTree(lazyTreeNodeMap, maps, parentId) {
            console.log("999", parentId)
            if (this.maps.get(parentId)) {
                const { tree, treeNode, resolve } = this.maps.get(parentId);
                this.$set(lazyTreeNodeMap, parentId, []);
                if (tree) {
                    this.load(tree, treeNode, resolve);
                }
            }
        },
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    const operation = this.form.id ? updateEnterprise : addEnterprise;
                    const successMsg = this.form.id ? "修改成功" : "新增成功";

                    operation(this.form).then(response => {
                        this.$modal.msgSuccess(successMsg);
                        this.open = false;

                        // 刷新对应的父节点
                        const parentId = this.form.parentId || 0;
                        if (parentId == 0) {
                            this.getList()
                        } else {

                            this.refreshLoadTree(
                                this.$refs.table.store.states.lazyTreeNodeMap,
                                this.maps,
                                this.form.parentId
                            );
                        }
                    });
                }
            });
        },
        handleDelete(row) {
            const ids = row.id;
            this.$modal.confirm('是否确认删除？').then(() => {
                return delEnterprise(ids);
            }).then(() => {
                this.$modal.msgSuccess("删除成功");
                const store = this.$refs.table.store;
                if (row.parentId != 0) {
                    const parentId = store.states.lazyTreeNodeMap[row.parentId];
                    const index = parentId.findIndex((child) => child.id == row.id);
                    parentId.splice(index, 1);
                } else {
                    this.getList()
                }
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('business/enterprise/export', {
                ...this.queryParams
            }, `enterprise_${new Date().getTime()}.xlsx`)
        },


        async load(tree, treeNode, resolve) {
            this.maps.set(tree.id, { tree, treeNode, resolve });
            this.parentId = tree.id
            try {
                const parentId = tree ? tree.id : null;

                // 如果是第三级节点，不加载子节点
                if (tree && tree.hierarchyType == 2) {
                    resolve([]);
                    return;
                }
                const params = { parentId };
                const response = await listEnterprise(params);

                // 设置 hasChildren 属性（只有第一级和第二级可能有子节点）
                const children = response.rows.map(item => ({
                    ...item,
                    hasChildren: item.hierarchyType != 2
                }));

                // 缓存子节点数据
                this.nodeChildrenMap.set(parentId, children);
                resolve(children);

                // 记录节点加载状态
                this.loadedNodes.add(parentId);
            } catch (error) {
                console.error("加载子节点失败:", error);
                resolve([]);
            }
        },
        async getList() {
            this.loading = true;
            this.queryParams.parentId = 0
            try {
                const response = await listEnterprise(this.queryParams);
                // 为每个根节点设置hasChildren属性
                this.enterpriseList = response.rows.map(item => ({
                    ...item,
                    hasChildren: item.hierarchyType != 2
                }));
                this.total = response.total;

                // 清除根节点缓存
                this.loadedNodes.delete(0);
                this.nodeChildrenMap.delete(0);
            } finally {
                this.loading = false;
            }
        }
    }
};
</script>
<style scoped>
.export-content {
    width: 600px;
    display: flex;
    justify-content: space-around;

}

.content-image {
    width: 200px;
    height: 200px;
    display: block;
}

.text-content {
    margin-top: 20px;
    font-size: 14px;
    line-height: 1.5;
    color: #666;
}
</style>
